<template>
  <!-- v-model="fieldValue" -->
  <!-- :label="label" -->
  <div style="height: 100%">
    <div class="btn" @click="show = true">选择</div>
    <van-popup v-model:show="show" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title="请选择所在地区"
        :field-names="{ text: 'name', value: 'id', children: 'children' }"
        :options="options"
        @close="show = false"
        @change="onChange"
        @finish="onFinish"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount } from 'vue'
import { gerAreaByCode } from '@/api/api.js'

const emit = defineEmits(['update:value', 'change', 'update:textValue'])
const props = defineProps({
  value: {
    type: Array
  },
  // label名称
  label: {
    type: String,
    default: '地区'
  },
  // 选择最终值是否只显示最后一级
  valueIsLast: {
    type: Boolean,
    default: false
  }
})

const show = ref(false)
const fieldValue = ref('')
const cascaderValue = ref('')
const options = ref([])
const initOptions = ref([])
const currentLevel = ref(1)
const state = reactive({
  areaCodeArray: []
})

const addTree = (selectedOptions, children, id) => {
  selectedOptions.forEach(item => {
    if (item.id == id) {
      item.children = children
    }
  })
}

const onChange = async ({ value, selectedOptions, tabIndex }) => {
  let res = await getNextArea(value)
  if (res.succeed && res.data.length > 0) {
    addTree(selectedOptions, res.data, value)
  } else {
    show.value = false
  }
}

const onFinish = ({ selectedOptions }) => {
  console.log(props.valueIsLast)
  if (props.valueIsLast) {
    fieldValue.value = selectedOptions[selectedOptions.length - 1].name
  } else {
    fieldValue.value = selectedOptions.map(option => option.name).join('/')
  }

  let arr = selectedOptions.map(option => option.id)
  console.log(selectedOptions[selectedOptions.length - 1])
  let code = selectedOptions[selectedOptions.length - 1].pid
  emit('update:value', code)
  emit('update:textValue', fieldValue.value)
  emit('change', code)
}

const getNextArea = async code => {
  let res = await gerAreaByCode(code)
  if (res.succeed) {
    return res
  }
}

const getFirstArea = async code => {
  let res = await getNextArea(code)
  console.log(res)
  options.value = res.data
  initOptions.value = res.data
}

onBeforeMount(() => {
  getFirstArea('440000')
})
</script>
<style lang="less" scoped>
:deep(.van-cell) {
  align-items: center;
}
:deep(.van-field__right-icon) {
  display: flex;
  align-items: center;
  img {
    width: 32px;
  }
}
:deep(.van-field__body) {
  font-size: 32px;
}
:deep(.van-field__right-icon) {
  padding: 0;
}
:deep(.van-field__control::-webkit-input-placeholder) {
  color: #000;
}

.btn {
  font-size: 36px;
  color: #4293f4;
}
</style>
